﻿using System;
using System.Web.UI;
using Legazpi.Payroll.DataAccess.DataObjects;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Ninject;
using Legazpi.Payroll.Web.Helpers;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

namespace Legazpi.Payroll.Web.Usercontrols
{
    public partial class EmployeeCashAdvance : System.Web.UI.UserControl
    {
        [Inject]
        public IEmployeeAdjustmentService _employeeAdjustmentService { get; set; }

        protected List<EmployeeAdjustment> Model { get; private set; }
        protected double TotalDebit { get; private set; }
        protected double TotalCredit { get; private set; }
        protected double TotalRunningBalance { get { return TotalCredit - TotalDebit; } }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["empid"]))
                {
                    int employeeId;
                    int.TryParse(Request.QueryString["empid"], out employeeId);
                    if (employeeId > 0)
                        //Update Data
                        Model = _employeeAdjustmentService.GetAllValidCashAdvanceByEmployeeId(employeeId).ToList();
                }
                //New Data
                Model = Model ?? new List<EmployeeAdjustment>();
                BindTable();
            }
        }

        #region Implementations
        void BindTable()
        {
            repeater.DataSource = Model;
            repeater.DataBind();
        }
        #endregion

        protected void repeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var literalRunningBal = e.Item.FindControl("literalRunningBal") as Literal;
                var literalDateAdded = e.Item.FindControl("literalDateAdded") as Literal;
                var debit = ((EmployeeAdjustment)e.Item.DataItem).Debit;
                var credit = ((EmployeeAdjustment)e.Item.DataItem).Credit;

                TotalDebit += debit;
                TotalCredit += credit;

                literalRunningBal.Text = (TotalCredit - debit).ToString("N");
                literalDateAdded.Text = ((EmployeeAdjustment)e.Item.DataItem).DateAdded.HasValue ? ((EmployeeAdjustment)e.Item.DataItem).DateAdded.Value.ToShortDateString() : string.Empty;
            }
        }


    }
}